package cn.jinjimi.app.custom.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.entity.Follow;
import cn.jinjimi.app.custom.event.CustomChangeEvent;
import cn.jinjimi.app.custom.iview.CustomArchivsView;
import cn.jinjimi.app.custom.manager.CustomsManager;
import cn.jinjimi.app.custom.ui.adapter.CustomArchivesAdapter;
import cn.jinjimi.app.custom.ui.fragment.MakeCardFragment;
import cn.jinjimi.app.custom.ui.view.CustomArchivesFootView;
import cn.jinjimi.app.custom.ui.view.CustomArchivesHeadView;
import cn.jinjimi.app.custom.ui.view.CustomArchivesMenuWindow;
import cn.jinjimi.app.custom.utils.CustomContactHelper;
import cn.jinjimi.app.entity.AppConfig.AppCustomersDTO;
import cn.jinjimi.app.presenter.CustomArchivesPresent;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.store.DatabaseManager;
import cn.jinjimi.app.main.activity.AllCardListActivity;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.biz.TipWindow;
import cn.jinjimi.app.main.widget.XListView.XListView;
import cn.jinjimi.app.bean.SharePrefKeys;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * 客户档案界面
 * <p/>
 * 包含客户基本信息
 * 客户保单数量,最近续保保单
 * 跟进记录列表
 */
public class CustomArchivesActivity extends ToolBarCommonActivity implements CustomArchivsView {

    private XListView mListView;
    private CustomArchivesAdapter mCustomArchivesAdapter;

    private CustomArchivesHeadView mHeaderView;
    private CustomArchivesFootView mFooterView;

    private CustomArchivesMenuWindow mPopupWindow;

    private CustomArchivesPresent mCustomArchivesPresent;

    private Custom mCustom;
    private long mCustomId;

    public static void launch(Context startActivity, Custom custom) {
        if (startActivity == null || custom == null)
            return;
        Intent intent = new Intent(startActivity, CustomArchivesActivity.class);
        intent.putExtra(BundleKey.PARAM_CUSTOM, custom);
        startActivity.startActivity(intent);
    }

    public static void launch(Context startActivity, long customId) {
        if (startActivity == null || customId == 0)
            return;
        Intent intent = new Intent(startActivity, CustomArchivesActivity.class);
        intent.putExtra(BundleKey.PARAM_CUSTOM_ID, customId);
        startActivity.startActivity(intent);
    }

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_custom_archives);
        if (getIntent().hasExtra(BundleKey.PARAM_CUSTOM)) {
            mCustom = (Custom) getIntent().getSerializableExtra(BundleKey.PARAM_CUSTOM);
            mCustomId = mCustom.customerId;
        } else if (getIntent().hasExtra(BundleKey.PARAM_CUSTOM_ID)) {
            mCustomId = getIntent().getLongExtra(BundleKey.PARAM_CUSTOM_ID, 0);
        }

        mCustom = DatabaseManager.getInstance().getCustomerDao().loadDeep(mCustomId);
        mCustomArchivesPresent = new CustomArchivesPresent(this, mCustom);
        setRightButton(R.drawable.nav_icon_more);
        setTitle(R.string.customer_archives_title);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        mHeaderView = new CustomArchivesHeadView(this);
        mFooterView = new CustomArchivesFootView(this);

        mListView = (XListView) findViewById(R.id.listview);
        mListView.setTransparentBg();
        mListView.setPullLoadEnable(false);
        mListView.setPullRefreshEnable(false);
        mListView.addHeaderView(mHeaderView);
    }

    protected void initListener() {
        findViewById(R.id.ll_follow).setOnClickListener(this);
        findViewById(R.id.ll_sms).setOnClickListener(this);
        findViewById(R.id.ll_call).setOnClickListener(this);
        findViewById(R.id.ll_insure).setOnClickListener(this);
        findViewById(R.id.ll_card).setOnClickListener(this);
        findViewById(R.id.ll_plan).setOnClickListener(this);
    }

    protected void initData() {
        ToastUtil.showLoading(this, getString(R.string.loading_data));
        mCustomArchivesPresent.getCustomArchivesData(mCustomId);

        mCustomArchivesAdapter = new CustomArchivesAdapter(CustomArchivesActivity.this);
        mListView.setAdapter(mCustomArchivesAdapter);

        if (mCustom != null)
            setCustomBaseInfo(mCustom);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.ll_follow:// 底部跟进
                openAddRecord();
                break;
            case R.id.ll_sms: // 底部短信
                makeMsg();
                break;
            case R.id.ll_call: // 底部电话
                makeCall();
                break;
            case R.id.ll_insure:// 底部投保
                gotoInsure();
                break;
            case R.id.ll_card:// 底部贺卡
                sendCard();
                break;
            case R.id.ll_plan:// 底部计划书
                makePlan();
                break;
        }
    }

    @Override
    protected void rightAction() {
        super.rightAction();
        showPopupWindow(getRightBtn());
    }

    @Override
    public void setCustomBaseInfo(Custom custom) {
        mCustom = custom;
        mHeaderView.setCustom(custom);
        mCustomArchivesAdapter.setCustom(mCustom);
    }

    @Override
    public void showToast(int resId) {
        ToastUtils.toastMessage(CustomArchivesActivity.this, resId);
    }

    /* 客户被删或为空的处理 */
    @Override
    public void customNull() {
        getAlertDialog().setTitle(getString(R.string.custom_null))
                .setRightBtn(getString(R.string.custom_i_know), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        CustomsManager.getInstance().deleteCustom(mCustom, true);
                        EventBus.getDefault().post(new CustomChangeEvent(mCustom, CustomChangeEvent.EVENT_DELETE));
                        finish();
                    }
                });
        getAlertDialog().setCancelable(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.ONE_BUTTON);
    }

    @Override
    public void setTagText() {
        mHeaderView.setTagText();
    }

    @Override
    public void finished() {
        finish();
    }

    @Override
    public void disloadingDialog() {
        hideLoadingIndicator();
    }

    /**
     * 展示右上角的试图,上面有跟进记录,联系客户,发贺卡等功能.
     *
     * @param view
     */
    private void showPopupWindow(View view) {
        if (mPopupWindow == null) {
            mPopupWindow = new CustomArchivesMenuWindow(this, mCustom);
        }
        mPopupWindow.showAsDropDown(view);
    }

    @Override
    public void setFollows(List<Follow> follows) {
        mCustomArchivesAdapter.setItems(follows);
        showTipView();
    }

    /**
     * 跟进记录为空时的导航图
     *
     * @param haveFollows
     */
    @Override
    public void addFootView(boolean haveFollows) {
        if (haveFollows) {
            mListView.removeFooterView(mFooterView);
        } else {
            mListView.removeFooterView(mFooterView);
            mListView.addFooterViewBeforeFootView(mFooterView);
        }
    }

    /* 打开添加跟进记录页面 */
    @EventTrace(EventID.APP_CUSTOMER_DETAIL_ADDFOLLOW)
    public void openAddRecord() {
        if (mCustom != null)
            AddFollowRecordActivity.launch(CustomArchivesActivity.this, mCustom, false, true);
    }

    /* 发短信 */
    @EventTrace(EventID.APP_CUSTOMER_DETAIL_BOTTOMNAV_MSG)
    public void makeMsg() {
        if (mCustom != null)
            new CustomContactHelper(CustomArchivesActivity.this, mCustom, CustomContactHelper.TypeMsg).contact();
    }

    /* 打电话 */
    @EventTrace(EventID.APP_CUSTOMER_DETAIL_BOTTOMNAV_MOBILE)
    public void makeCall() {
        if (mCustom != null)
            new CustomContactHelper(CustomArchivesActivity.this, mCustom, CustomContactHelper.TypeCall).contact();
    }

    /* 前往投保的页面 */
    @EventTrace(EventID.APP_CUSTOMER_DETAIL_BOTTOMNAV_INSURE)
    public void gotoInsure() {

    }

    /* 发送贺卡 */
    @EventTrace(EventID.APP_CUSTOMER_DETAIL_BOTTOMNAV_SENDCARD)
    public void sendCard() {
        if (mCustom != null) {
            Intent holiday = new Intent(this, AllCardListActivity.class);
            holiday.putExtra("title", mCustom.name);
            holiday.putExtra("customId", String.valueOf(mCustom.customerId));
            holiday.putExtra("enter", MakeCardFragment.ENTER.INFO.getEnter());
            startActivity(holiday);
        }
    }

    /* 打开计划书界面 */
    @EventTrace(EventID.APP_CUSTOMER_DETAIL_BOTTOMNAV_VPLAN)
    public void makePlan() {
        if (mCustom != null) {
            AppCustomersDTO.Config config = AppCustomersDTO.getConfig();
            if (config != null && !TextUtils.isEmpty(config.getVplanUrl())) {
                Router.create(CustomArchivesActivity.this, config.getVplanUrl()).addParam(BundleKey.PARAM_CUSTOM, mCustom).open();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCustomArchivesPresent.onDestroy();
        mCustomArchivesPresent = null;
    }

    /* 2.3.0新增的个人资料按钮提示 */
    TipWindow tipWindow;

    private void showTipView() {
        if (PreferenceManager.getBooleanData(SharePrefKeys.PREF_CUSTOM_ARCHIEVE_INFO_TIP))
            return;

        if (AccountManager.getInstance().isUpdateAccount())
            return;

        if (tipWindow == null) {
            tipWindow = new TipWindow(CustomArchivesActivity.this)
                    .setkey(SharePrefKeys.PREF_CUSTOM_ARCHIEVE_INFO_TIP)
                    .setText(R.string.tip_complete_info)
                    .setRightMargin(R.dimen.dp_20)
                    .setAlpha(60);
        }
        tipWindow.showAsDropDown(mHeaderView.getInfoView());
    }

    private void dismisTipView() {
        if (tipWindow != null && tipWindow.isShowing())
            tipWindow.dismiss();
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismisTipView();
    }
}